<script setup lang="ts">
import { ref, onMounted, onActivated, computed } from 'vue'
import { taskListNew } from '@/api/task'
import type { taskSearch } from '@/api/type'
import taskItem from '@/components/taskItem/taskItem.vue'
import { useRouter, onBeforeRouteLeave } from 'vue-router'
import { useAppStore } from '@/store/modules/app'
import { useKeepPage } from '@/hooks/web/useKeepPage'
useKeepPage(['addTask', 'followFeedback'])

const appStore = useAppStore()
const userInfo = ref(appStore.getUserInfo)
const page = ref(0)
const totalPage = ref(1)
const content = ref<any[]>([])
const loading = ref(false)
const finished = ref(false)
const search = function () {
  const searchForm = appStore.getSearchForm
  loading.value = true
  let searchData = {
    pageNo: page.value,
    pageSize: 10,
    userId: userInfo.value.id,
    ...searchForm,
    taskActive: '4'
  }
  taskListNew({ ...searchData }).then((res) => {
    loading.value = false
    totalPage.value = res.totalPages
    content.value = [...content.value, ...res.aaData]
    if (page.value <= totalPage.value) {
      finished.value = true
    }
  })
}
onBeforeRouteLeave(() => {
  const data = {
    page: page.value,
    totalPage: totalPage.value,
    content: content.value,
    scrollTop: document.documentElement.scrollTop
  }
  appStore.setPageData('newTask', data)
})
onActivated(() => {
  const pageData = appStore.getPageData('newTask')
  userInfo.value = appStore.getUserInfo
  if (pageData) {
    // page.value = pageData.page
    // totalPage.value = pageData.totalPage
    // content.value = pageData.content
    document.documentElement.scrollTo(0, pageData.scrollTop)
  } else {
    onRefresh()
  }
})
// onMounted(() => {
//   search()
// })

const onRefresh = function () {
  content.value = []
  page.value = 1
  search()
}
const onLoad = function () {
  if (page.value < totalPage.value) {
    page.value += 1
    search()
  } else {
    loading.value = false
    finished.value = true
  }
}

const { push } = useRouter()
const onClickRight = function () {
  push({
    name: 'search'
  })
}
</script>

<template>
  <van-nav-bar title="最新任务" fixed placeholder z-index="10" @click-right="onClickRight">
    <template #right>
      <van-icon name="search" size="18" />
    </template>
  </van-nav-bar>
  <div class="listBox">
    <van-pull-refresh v-model="loading" @refresh="onRefresh" style="">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        offset="100"
        @load="onLoad"
      >
        <taskItem v-for="item of content" :key="item.id" :item="item" />
      </van-list>
    </van-pull-refresh>
  </div>
  <van-back-top bottom="80">
    <van-button
      round
      type="primary"
      size="small"
      icon="arrow-up"
      style="width: 42px; height: 42px"
    ></van-button>
  </van-back-top>
</template>

<style lang="less" scoped>
.listBox {
  padding: 0 12px;
  background: var(--van-background);
}
</style>
